<template>
  <div class="customer-form-container">
    <el-card class="customer-form-card">
      <h2>添加客户</h2>
      <el-form
        ref="customerForm"
        :model="customer"
        :rules="rules"
        label-width="80px"
        label-position="top"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="名称" prop="name" required>
          <el-input
            v-model="customer.name"
            placeholder="请输入客户名称"
            required
          ></el-input>
          <div class="form-help">请输入客户的全称，最多20个字符。</div>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" required>
          <el-input
            v-model="customer.email"
            type="email"
            placeholder="请输入客户邮箱"
            required
          ></el-input>
          <div class="form-help">请输入有效的邮箱地址，用于联系客户。</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { addCustomer } from '@/api/customers';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

export default {
  setup() {
    const router = useRouter();
    const customer = ref({ name: '', email: '' });

    // 定义验证规则
    const rules = {
      name: [
        { required: true, message: '请输入客户名称', trigger: 'blur' },
        { max: 20, message: '名称最多20个字符', trigger: 'blur' },
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] },
      ],
    };

    const handleSubmit = async () => {
      const form = this.$refs.customerForm;
      form.validate(async (valid) => {
        if (valid) {
          try {
            await addCustomer(customer.value);
            ElMessage.success('客户添加成功！');
            router.push('/customers'); // 提交后返回客户列表页面
          } catch (error) {
            ElMessage.error('添加客户失败，请稍后重试。');
            console.error('Error creating customer:', error);
          }
        } else {
          ElMessage.error('表单填写有误，请检查后再试。');
        }
      });
    };

    return {
      customer,
      rules,
      handleSubmit,
    };
  }
};
</script>

<style scoped>
.customer-form-container {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.customer-form-card {
  width: 100%;
  max-width: 400px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}

.form-help {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
</style>